<template>
  <div style="background-color: #fff;height: 100%;padding: 10px;">
    <HeaderTitle title="导入信息"></HeaderTitle>
    <div style="margin-bottom: 20px;">
      <a-upload :showUploadList="false" v-show="true" accept="xlsx" name="file" :headers="headers"
        :customRequest="customRequest">
        <Button type="primary">导入Excel</Button>
      </a-upload>
      <Button style="margin: 0 15px;" type="primary" @click="impExcel()">模板下载</Button>
      <Button type="primary" :disabled="!state.checkedList.length" @click="allDelete()">批量删除</Button>
    </div>
    <vxe-table :loading-config="{ icon: 'vxe-icon-indicator roll', text: '正在拼命删除中' }" :loading="loading" border
      ref="xTable1" :data="tableData" @checkbox-all="checkboxChangeFn" max-height="600px" align="center" show-overflow
      @checkbox-change="checkboxChangeFn">
      <vxe-column type="checkbox" width="60"></vxe-column>
      <vxe-column v-for="item in baseColumns" :key="item.field" :field="item.field" :title="item.title"></vxe-column>
      <vxe-column field="sampleAddress" title="操作">
        <template #default="{ row }">
          <Button @click="caozuo(row)">删除</Button>
        </template>
      </vxe-column>
    </vxe-table>
    <p style="margin-top: 20px;">记录总数 : {{ tableData.length }}</p>
    <div style="margin: 20px ; width: 100%;display: flex;justify-content: center;">
      <Button style="margin: 0 15px;" @click="reset()">重置</Button>
      <Button type="primary" :disabled="tableData.length == 0" @click="save()">保存登记</Button>
    </div>
    <a-drawer destroyOnClose @close="onclose" v-model:visible="visible"
      :footerStyle="{ display: 'flex', justifyContent: 'center' }" class="custom-class" style="" width="80%"
      placement="right">
      <a-row :gutter="[0, 10]">
        <a-col :span="8">
          <a-form :model="dynamicValidateForm" name="basic" :label-col="{ span: 4 }" :wrapper-col="{ span: 10 }"
            autocomplete="off">
            <a-form-item name="area" label="样本模板">
              <a-select @change="change" v-model:value="dynamicValidateForm.area" :options="areas" />
            </a-form-item>
          </a-form>
        </a-col>
      </a-row>
      <a-transfer :list-style="{
        width: '300px',
        height: '500px',
        border: 0,
      }" v-model:target-keys="targetKeys" :data-source="mockData" show-search :operations="['添加导出', '移除导出']"
        :filter-option="filterOption" :render="(item) => item.title" @change="handleChange" @search="handleSearch" />
      <HeaderTitle :title="title"></HeaderTitle>
      <a-row :gutter="[0, 10]">
        <a-col :span="4">
          <a-form :model="dynamicValidateForm" name="basic" :label-col="{ span: 8 }" :wrapper-col="{ span: 14 }"
            autocomplete="off">
            <a-form-item name="area" label="样本数量">
              <a-input type="number" v-model:value="dynamicValidateForm.num" />
            </a-form-item>
          </a-form>
        </a-col>
        <a-col :span="8">
          <Button type="primary" @click="scan">确定</Button>
        </a-col>
      </a-row>
      <div class="card_wrap">
        <div class="c_item" v-for="(item, index) in tableData1" :key="item">
          <a-input @change="inpChange()" v-model:value="item.serial"></a-input>
        </div>
      </div>
      <template #footer>
        <Button style="margin-right: 10px" @click="onclose">取消</Button>
        <Button type="primary" @click="exportSelect">导出Excel</Button>
      </template>
    </a-drawer>
  </div>
  <!-- 打印表格 -->
</template>
<script setup lang="tsx">
import { ref, reactive } from 'vue';
import { Button, message, Modal } from 'ant-design-vue';
import columns, { TableColumnList } from './columns';
import { getlistData, deletelistData, deleteAlllistData } from '../../api/registration_sample';
import { resetting, queryimport } from '../../api/import_Information';
import { getSampleTemplate } from '../../api/template-management';
import { commonSearch } from '@/api/common/common_data';
import { getExportTemplate, uploadExcel } from '@/api/utils';
import { getcustomerFormData } from '@/api/public';
import { addSpecimenType } from '@/libs/utils';
import HeaderTitle from '@/components/headerTitle.vue';
const visible = ref(false);
const tableData = ref([]);
// 上传附件
const headers = {
  authorization: 'authorization-text',
};
const state = reactive({
  checkedList: [],
});
const loading = ref(false)
// 文件上传点击事件
const customRequest = async (e) => {
  let data = new FormData();
  data.append('file', e.file); //如果还有其他参数复制就行了
  await uploadExcel(data);
  fetchData()
};
const num = reactive({
  max: 0,
  min: 0,
});
const title = ref(`编码信息  (${num.min}/${num.max})`);
let baseColumns: TableColumnList = [
  ...columns
];
const caozuo = async (row) => {
  Modal.confirm({
    title: '确认删除吗?',
    onOk() {
      deletelistData(row.id).then((res) => {
        fetchData()
      });
    },
    onCancel() {
      console.log('Cancel');
    },
  });
}
const fetchData = async () => {
  loading.value = false
  let queryOpt = {
    pageSize: 20000,
    pageNum: 1,
    isImport: 1,
  };
  const { result } = await getlistData(queryOpt);
  result.data.forEach(item => {
    if (item?.unit == 1) item.capacity = `${item?.capacity ? item?.capacity : 0}ml`
    if (item?.unit == 2) item.capacity = `${item?.capacity ? item?.capacity : 0}μl`
  })
  addSpecimenType(result.data);
  tableData.value = result.data
};
fetchData()
const tableData1: any = ref([]);
const mockData = ref([]);
const dynamicValidateForm = reactive({
  area: 'specimen_fields',
  num: 0,
});
const areas = ref();
const SampleTemplate = async () => {
  const { result } = await getSampleTemplate(null);
  result.data.forEach((item) => {
    item.label = item.name;
    item.value = item.id;
  });
  areas.value = result.data;
  areas.value.push({ label: '默认模板', value: 'specimen_fields' });
  // 请求表单列表
  let params = {
    orderBy: [
      {
        field: 'sortIndex',
        order: 'asc',
      },
    ],
    groupId: 'specimen_fields',
  };
  const commonData = await commonSearch(params);
  const keys = [];
  const mData = [];
  let arr = commonData.result.filter(item => item.editType == 2)
  arr.forEach((item, i) => {
    const data = {
      key: String(item.id),
      title: item.name,
      editType: item.editType,
    };
    if (data.chosen) {
      keys.push(data.key);
    }
    mData.push(data);
  });
  mockData.value = mData;
  targetKeys.value = keys;
};
SampleTemplate();
// 模板部分
const change = async (id) => {
  let { result } = await getcustomerFormData({ groupId: id });
  const keys = [];
  const mData = [];
  let arr = result.filter(item => item.editType == 2)
  if (id == 'specimen_fields') {
    arr.forEach((item) => {
      const data = {
        key: String(item.id),
        title: item.name,
        editType: item.editType,
      };
      if (data.chosen) {
        keys.push(data.key);
      }
      mData.push(data);
    });
  } else {
    arr.forEach((item) => {
      const data = {
        key: String(item.id),
        title: item.name,
        chosen: true,
        disabled: true,
        editType: item.editType,
      };
      if (data.chosen) {
        keys.push(data.key);
      }
      mData.push(data);
    });
  }

  mockData.value = mData;
  targetKeys.value = keys;
};
//穿梭框部分
const targetKeys = ref<string[]>([]);
const filterOption = (inputValue: string, option) => {
  return option.title.indexOf(inputValue) > -1;
};
const handleChange = (keys: string[], direction: string, moveKeys: string[]) => {
  console.log(keys, direction, moveKeys);
};

const handleSearch = (dir: string, value: string) => {
  console.log('search:', dir, value);
};
const impExcel = () => {
  visible.value = true;
};
// excel导出
const exportSelect = async () => {
  let arr = mockData.value.filter((item) => item.editType == 2);
  message.success('正在导出，请稍候');
  let arrTitle = arr.map((item) => item.title).join(',')
  let arrKey = arr.map((item) => item.key).join(',')
  let serial = tableData1.value.map(item => item.serial).join(',')
  const res = await getExportTemplate(arrTitle, arrKey, dynamicValidateForm.area, serial);
  let url = window.URL.createObjectURL(
    new Blob([res], {
      type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
    }),
  );
  let link = document.createElement('a');
  link.style.display = 'none';
  link.href = url;
  link.setAttribute('download', '模板信息');
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link); // 下载完成移除元素
  window.URL.revokeObjectURL(url); // 释放掉blob对象
  onclose();
};
const inpChange = () => {
  num.min = tableData1.value.filter(item => item.serial != '').length
  title.value = `编码信息  (${num.min}/${num.max})`;
};
//编码部分
const scan = async () => {
  if (dynamicValidateForm.num > 100 || dynamicValidateForm.num < 0) {
    message.warning('样本数量应该为1-100');
    return (dynamicValidateForm.num = 0);
  }
  tableData1.value = []
  for (let i = 0; i < dynamicValidateForm.num; i++) {
    tableData1.value.push({ serial: '', id: i })
  }
  num.max = tableData1.value.length;
  title.value = `编码信息  (${num.min}/${num.max})`;
};
const allDelete = async () => {
  await deleteAlllistData(state.checkedList.map((item) => item.id).join(','));
  fetchData()
};
const checkboxChangeFn = ({ records }) => {
  state.checkedList = records;
};
const onclose = () => {
  visible.value = false;
  tableData1.value = []
  dynamicValidateForm.num = 0
  num.min = 0
  num.max = 0
  title.value = `编码信息  (${num.min}/${num.max})`;
};
// 重置
const reset = async () => {
  Modal.confirm({
    title: '确认重置吗?',
    onOk() {
      loading.value = true
      try {
        resetting({ specimenIds: tableData.value.map(item => item.specimenId) }).then((res) => {
          fetchData()
          loading.value = false
        });
      } catch (error) {
        loading.value = false
      }

    },
    onCancel() {
      console.log('Cancel');
    },
  });

}
// 保存
const save = async () => {
  Modal.confirm({
    title: '确认保存登记吗?',
    onOk() {
      loading.value = true
      try {
        queryimport({ specimenIds: tableData.value.map(item => item.specimenId) }).then((res) => {
          fetchData()
        });
        loading.value = true
      } catch (error) {
        loading.value = false
      }

    },
    onCancel() {
      console.log('Cancel');
    },
  });
}
</script>
<style lang="less" scoped>
.card_wrap {
  // 大盒子
  width: 98%;
  display: flex;
  flex-wrap: wrap;
  justify-content: flex-start; // 替代原先的space-between布局方式
}

.c_item {
  // 每个item
  flex: 1;
  height: 30px;
  // border: 1px solid #ccc;
  width: calc((100% - 10px) / 10); // 这里的10px = (分布个数3-1)*间隙5px, 可以根据实际的分布个数和间隙区调整
  min-width: calc((100% - 10px) / 10); // 加入这两个后每个item的宽度就生效了
  max-width: calc((100% - 10px) / 10); // 加入这两个后每个item的宽度就生效了

  &:nth-child(10n) {
    // 去除第3n个的margin-right
    margin-right: 0;
  }
}
</style>
